package com.lagou.filter;

import com.lagou.MethodCalledTimeInfo;
import com.lagou.tool.PDPrintHelper;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Activate(group = CommonConstants.CONSUMER)
public class TPMonitorFilter implements Filter {
    private static final Logger LOG = LoggerFactory.getLogger(TPMonitorFilter.class);

    /**
     * PD90、PD99信息打印帮助者
     */
    private PDPrintHelper pdPrintHelper = new PDPrintHelper();


    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long startTime = 0l;
        long endTime = 0l;
        try {
            startTime = System.currentTimeMillis();
            // 执行方法
            Result result = invoker.invoke(invocation);
            endTime = System.currentTimeMillis();
            // 保存本次方法调用时间信息，并触发打印PD90、PD99
            pdPrintHelper.put(new MethodCalledTimeInfo(invocation.getMethodName(), startTime, endTime - startTime));

            return result;

        } finally {
            LOG.info("{},耗时: {}ms", invocation.getMethodName(), endTime - startTime);
        }

    }
}
